package codecs

import "errors"

var (
	errShortPacket          = errors.New("packet is not large enough")
	errNilPacket            = errors.New("invalid nil packet")
	errTooManyPDiff         = errors.New("too many PDiff")
	errTooManySpatialLayers = errors.New("too many spatial layers")
	errUnhandledNALUType    = errors.New("NALU Type is unhandled")
)

var amr_nbFrameLen = []int{95, 103, 118, 134, 148, 159, 204, 244, 39}
var amr_wbFrameLen = []int{132, 177, 253, 285, 371, 365, 397, 461, 477, 40}
var wbSpeechFrameBytes = []int{18, 23, 33, 37, 41, 47, 51, 59, 61, 0, 0, 0, 0, 0, 0, 0}
var CMR = []byte{1, 1, 1, 1}

const (
	PCMAPayloadType   = 8
	PCMAPayLoadLength = 160
	// MAX_MTU = 1600 // 1388 // 578 or 1400 - 12, 1600 default.
)

// combine two wave files. length: PCMAPayLoadLength
func Combine4Bytes(sourceOne [][]byte, sourceTwo [][]byte) (rtp_payload [][]byte) {
	// 语音帧 copy...
	for index := 0; index < len(sourceOne); index++ {
		rtp_payload = append(rtp_payload, sourceOne[index][:])
	}

	for index := 0; index < len(sourceTwo); index++ {
		rtp_payload = append(rtp_payload, sourceTwo[index][:])
	}
	return rtp_payload
}

func Bytes2Bits(data []byte) []byte {
	bin := make([]byte, 0)
	for _, v := range data {
		for i := 0; i < 8; i++ {
			move := uint(7 - i)
			bin = append(bin, uint8((v>>move)&1))
		}
	}
	return bin
}

// 二进制数组转字节数组
func Bits2Bytes(data []byte) []byte {
	bytes := make([]byte, 0)
	for i := 0; i < len(data); i += 8 {
		bytes = append(bytes, (data[i]<<7)+(data[i+1]<<6)+(data[i+2]<<5)+
			(data[i+3]<<4)+(data[i+4]<<3)+(data[i+5]<<2)+(data[i+6]<<1)+(data[i+7]))
	}
	return bytes
}

func min(a, b int) int {
	if a < b {
		return a
	}
	return b
}

// audioDepacketizer is a mixin for audio codec depacketizers
type audioDepacketizer struct{}

func (d *audioDepacketizer) IsPartitionTail(marker bool, payload []byte) bool {
	return true
}

func (d *audioDepacketizer) IsPartitionHead(payload []byte) bool {
	return true
}

// videoDepacketizer is a mixin for video codec depacketizers
type videoDepacketizer struct{}

func (d *videoDepacketizer) IsPartitionTail(marker bool, payload []byte) bool {
	return marker
}
